package com.yymx.toback.common.util;

import com.alibaba.fastjson.JSON;

import com.yymx.toback.common.base.BaseResult;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Description:返回json到前台工具类
 */
@Slf4j
public class ResponseUtil {

    public static void write(HttpServletResponse response, String code , String message){
        if(response == null){
            return;
        }
        response.setCharacterEncoding("utf-8");
        try {
            PrintWriter out = response.getWriter();
            response.setContentType("application/json; charset=utf-8");
            BaseResult baseResult = new BaseResult(code,message,new Object());
            Object json = JSON.toJSON(baseResult);
            out.print(json);
            out.flush();
            out.close();
        } catch (IOException e) {
            log.error("获取response错误 {} ",e.getMessage() );
        }
    }

    public  static void streamWrite(HttpServletResponse response, String code , String message){
        if(response == null){
            return;
        }
        response.reset();
        response.setCharacterEncoding("utf-8");
        ServletOutputStream output = null;
        try {
            output = response.getOutputStream();
            response.setContentType("application/json; charset=utf-8");
            BaseResult baseResult = new BaseResult(code,message,new Object());
            Object json = JSON.toJSON(baseResult);
            output.write(json.toString().getBytes());
            output.flush();
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public  static void streamWrite(HttpServletResponse response, String code , String message, Object data){
        if(response == null){
            return;
        }
        response.reset();
        response.setCharacterEncoding("utf-8");
        ServletOutputStream output = null;
        try {
            output = response.getOutputStream();
            response.setContentType("application/json; charset=utf-8");
            BaseResult baseResult = new BaseResult(code,message,data);
            Object json = JSON.toJSON(baseResult);
            output.write(json.toString().getBytes());
            output.flush();
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

